<?php
namespace api\modules\v1\models\gift;

use api\modules\v1\models\Common;
use api\modules\v1\models\friend\Friend;
use api\modules\v1\models\user\User;
use common\models\CacheKeys;
use common\models\Functions;
use common\models\im\Im;
use common\models\Status;
use common\models\userFund\UserMoneyLog;
use yii\base\Exception;
use yii\helpers\ArrayHelper;
use Yii;
/**
 * This is the model class for table "goods".
 *
 * @property int $id
 * @property string $name
 */
class GiftLog extends \common\models\gift\GiftLog
{
    /**
     * 列表
     * @return array
     */
    public function getList(){
        try {
            $user = Yii::$app->getUser()->getIdentity()->toArray();
            $userId = $user['id'];

            $page = Yii::$app->request->get('page',1);
            $size = Yii::$app->request->get('size',20);
            $categoryId = Yii::$app->request->get('category_id','');
            //类型  1：我收到  2：某个用户收到
            $type = (int) Yii::$app->request->get('type',0);
            $code = (int) Yii::$app->request->get('code',0);  // 查看具体用户的礼物

            $where = $andWhere = [];
            if ($categoryId) {
                $where['category_id'] = $categoryId;
            }

            if (!$type && in_array($type,[1,2])) {
                throw new Exception('类型不合法！');
            }

            // 查看具体某个用户
            if($code && $type == 2){
                $receiveUser = User::getOneByWhere(['tx_code' => $code]);
                if (!$receiveUser) {
                    throw new Exception('未知用户礼物信息！');
                }
                //查看具体用户的礼物
                $where['receive_user_id'] = $receiveUser['id'];
            }

            if($type == 1){
                //我的
                $where['receive_user_id'] = $userId;
            }


            static::setPaginationForApi($page);
            $offset = ($page - 1) * $size;
            $list = static::getObjectByAndWhere($where,$andWhere,["*",'count(1) as giftNum'],'id ASC',$offset,$size)->with([
                'gift' => function($q) {
                    $q -> select(['id','name','coin','icon','cartoon_url']);
                }
            ])->groupBy('gift_id')->asArray()->all();

            $result = [];
            foreach ($list as $k => $v) {
                $singleGiftInfo = ArrayHelper::getValue($v,'gift',[]);
                $tmp = [
                    'name' => (string) $singleGiftInfo['name'] ?? '',
                    'icon' => $singleGiftInfo['icon'] ? $this->getImages($singleGiftInfo['icon']) : '',
                    'num' => (int) $v['giftNum'],
                ];
                $result[] = $tmp;
            }
            $data['data'] = $result;
            return Functions::formatRestAPI(0, '', $data);
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '数据异常');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }




}
